package com.security.control.web.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @author imoot@gamil.com
 * @date 2018/12/15 0015 11:56
 * --自定义拦截器（声明Component后需要配置在WebConfig中）
 * --拦截器会拦截包括框架、自定义的controller
 * --可以拿到原始的http请求响应信息和要执行的方法信息，拿不到传递到方法中的形参的值
 */
@Component
public class TimeInterceptor implements HandlerInterceptor {

    @Override
    //controller调用前被调用
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("time preHandler");
        System.out.println(((HandlerMethod) handler).getBean().getClass().getName());
        System.out.println(((HandlerMethod) handler).getMethod().getName());
        request.setAttribute("startTime", new Date().getTime());
        return true;//false不执行controller中的方法，为true则执行
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("time postHandler");
        Long start = (Long) request.getAttribute("startTime");
        System.out.println("time interceptor use time:" + (new Date().getTime() - start));
    }

    @Override
    //controller调用完成后被调用（即使发生异常，也会被调用）
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("time afterHandler");
        Long start = (Long) request.getAttribute("startTime");
        System.out.println("time interceptor use time:" + (new Date().getTime() - start));
        System.out.println("exception is" + ex);
    }
}
